<?php


namespace App\Admin\Forms;


use App\Constants\VipLogOperateTypeConstant;
use App\Models\Member;
use App\Models\MemberVipLog;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class OperateMemberVip extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle($input)
    {
        $isVip = $input['is_vip'] ?? 0;
        $endDate = $input['vip_end_time'] ?? '';

        $id = $this->payload['id'];

        $member = Member::find($id);
        if (!$member) {
            return $this->response()->error('会员不存在');
        }

        if ($isVip) {
            if (!$endDate) {
                return $this->response()->error('vip到期时间不能为空');
            }

            if (strtotime($endDate) < time()) {
                return $this->response()->error('vip到期时间不能小于当前时间');
            }
        }

        $admin = Admin::user();

        try {
            DB::beginTransaction();

            $member->update([
                'is_vip'       => $isVip,
                'vip_end_time' => $endDate ? strtotime($endDate) : 0
            ]);

            MemberVipLog::create([
                'member_id'    => $id,
                'operate_type' => VipLogOperateTypeConstant::ADMIN,
                'content'      => sprintf('%s[ID:%d]修改vip信息', $admin->username, $admin->id),
            ]);

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            log_exception('变更会员vip信息异常', $e);
            return $this->response()->error('操作失败');
        }

        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $payload = $this->payload;

        $endDate = $payload['vip_end_time'] ?? '' ? date('Y-m-d H:i:s', $payload['vip_end_time']) : '';

        $this->radio('is_vip', '是否vip')->options([0 => '否', 1 => '是'])->value($payload['is_vip'] ?? 0);
        $this->datetime('vip_end_time', 'vip到期时间')->value($endDate);
    }
}
